<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="../vue.js"></script>
  </head>
  <body>
    <!-- 
      跨组件传递数据:
      建立事件中心
      const eventBus = new Vue()
      传递数据-----要传数据的组件方法里写
      eventBus.$emit('自定义事件名',传递的数据)
      接收数据-----接受的组件挂载完成（接收组件的mounted里写：
      eventBus.$on('自定义事件名'[,callback])
      销毁事件中心--beforeDestroy(){}里写
      eventBus.$off('自定义事件名')
     -->
    <div id="app">
      <my-grandfather></my-grandfather>
    </div>
    <!-- 爷爷组件 -->
    <template id="grandfather">
      <div>
        <h1>爷爷组件--{{count}}</h1>
        <button @click="send">传递</button>
        <my-father></my-father>
      </div>
    </template>
    <!-- 父组件 -->
    <template id="father">
      <div>
        <h3>父组件--</h3>
        <my-son></my-son>
      </div>
    </template>
    <!-- 子组件 -->
    <template id="son">
      <div>
        <h5>子组件--{{count}}</h5>
      </div>
    </template>
    <script>
      // ***事件总线
      const bus = new Vue();
      // ***子组件
      const Son = {
        template: "#son",
        data() {
          return {
            count: null,
          };
        },
        mounted() {
          // bus.$on(事件名，)
          bus.$on("send", (data) => {
            this.count = data;
          });
        },
        beforeDestroy() {
          //清空$on的挂起状态
          bus.$off("send");
        },
      };
      // 父组件
      const Father = {
        template: "#father",
        components: {
          "my-son": Son,
        },
      };
      // 爷爷组件
      const GrandFather = {
        template: "#grandfather",
        components: {
          "my-father": Father,
        },
        data() {
          return {
            count: 666,
          };
        },
        methods: {
          send() {
            // bus.$emit(事件名，传递的数据)
            bus.$emit("send", this.count);
          },
        },
      };
      new Vue({
        el: "#app",
        components: {
          "my-grandfather": GrandFather,
        },
      });
    </script>
  </body>
</html>
